package context;

import entity.Function;
import entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.FunctionService;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by asus on 2017/6/17.
 */
@Service
public class NativeCache {
    private Map<Long, Function> functionMap=new HashMap<>();
    private Map<Long,List<Role>> userRoleMap=new HashMap<>();
    @Autowired
    private FunctionService functionService;

    //类似于构造器
    @PostConstruct
    public void init(){
        List<Function> functionList=functionService.getAllFunctions();
        for(Function function:functionList){
            functionMap.put(function.getId(),function);
        }
        System.out.println("functions add ok");
    }

    public List<Function> getFunctions(){
        if(functionMap.isEmpty()){
            init();
        }
        //为什么要重新new一个？
        return new ArrayList<Function>(functionMap.values());
    }

    public void addFunction(Function function){
        functionMap.put(function.getId(),function);
    }

    public void replaceFunction(Function function){
        if(functionMap.containsKey(function.getId())){
            functionMap.remove(function.getId());
            functionMap.put(function.getId(),function);
        }
    }

    public void removeFunction(Long functionId){
        if(functionMap.containsKey(functionId)){
            functionMap.remove(functionId);
        }
    }

    public void setRoles(Long userId,List<Role> roles){
        userRoleMap.put(userId,roles);
    }

    public List<Role> getRoles(Long userId){
        return userRoleMap.get(userId);
    }

    public Function getFunction(Long id){
        return functionMap.get(id);
    }
}
